package com.gl.emms.whale.ui;

import java.util.HashMap;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import cn.smssdk.gui.RegisterPage;

import com.gl.emms.client.android.EMMSPushManager;
import com.gl.emms.nio.mutual.ReplyBody;
import com.gl.emms.whale.R;
import com.gl.emms.whale.app.Constant;
import com.gl.emms.whale.app.MyApplication;
import com.gl.emms.whale.app.WhaleMonitorActivity;
import com.gl.emms.whale.util.HeartBeatInfoSaveUtil;
import com.gl.emms.whale.util.MD5;
import com.gl.emms.whale.util.RoomViewEntity;
import com.gl.emms.whale.util.SharePreferenceUtil;
import com.gl.emms.whale.util.UpdateManager;

/**登陆界面类
 * @author ganlinux
 *
 */
public class LoginActivity extends WhaleMonitorActivity implements
OnClickListener {
	private boolean canReceive = false;//是否处理接收 
	private Handler mHandler;//消息处理器
	private Runnable mRunnable;//线程接口

	private RoomViewEntity roomViewEntity;
	private UpdateManager mUpdateManager;//更新提示

	//private BadgeView testbadgeView = null;

	private EditText accountEdit,pwdEdit;
	private Button mBtnLogin;
	private Button mBtnRegister;
	private CheckBox rememberPassword ;
	//private WaveView waveView;
	private View mMoreView;// “更多登录选项”的view
	private boolean mShowMenu = false;// “更多登录选项”的内容是否显示
	private View mMoreMenuView;// “更多登录选项”中的内容view
	private ImageView mMoreImage;// “更多登录选项”的箭头图片
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		MyApplication.getInstance().addActivity(this);
		setContentView(R.layout.activity_login);

		initViews();
		checkUpdate();

		mHandler = new Handler() {  
			@Override public void handleMessage(Message msg) {//覆盖handleMessage方法  
				switch (msg.what) {//根据收到的消息的what类型处理  
				case 0x01:  
					hideProgressDialog();
					showToask("登陆超时,请重试");
					canReceive = false;
					
					break;  
				default:  
					super.handleMessage(msg);//这里最好对不需要或者不关心的消息抛给父类，避免丢失消息  
					break;  
				}  
			}  
		};
		
		mRunnable = new Runnable() {
			public void run() {    
			    //execute the task    
			    	Message message = new Message();
					message.what = 0x01;
					mHandler.sendMessage(message);
					
			    } 
		};
		//短信验证初始化
		SMSSDK.initSDK(this, "466bd320cc1c", "0724485e1d20be5684efa097da3883bd");
		//waveView.start();
	}

	/**
	 * 初始化界面
	 * @time 2014年11月13日下午12:47:19
	 * @return void
	 * @user ganlinux
	 */
	public void initViews() {
		mMoreView = findViewById(R.id.more);

		mMoreMenuView = findViewById(R.id.moremenu);
		mMoreImage = (ImageView) findViewById(R.id.more_image);
		mMoreView.setOnClickListener(this);


		accountEdit = (EditText)findViewById(R.id.lgoin_accounts);
		pwdEdit = (EditText)findViewById(R.id.login_password);
		mBtnRegister = (Button) findViewById(R.id.regist_btn);
		mBtnRegister.setOnClickListener(this);

		mBtnLogin = (Button) findViewById(R.id.login_btn);
		mBtnLogin.setOnClickListener(this);
		//waveView = (WaveView) findViewById(R.id.waveview);
		
		SharePreferenceUtil util = new SharePreferenceUtil(this, Constant.SAVE_USERINFO);
		accountEdit.setText(util.getUserName());
		rememberPassword = (CheckBox)findViewById(R.id.auto_save_password);
		if (rememberPassword.isChecked()) {
			pwdEdit.setText(util.getPassword());
		}
	}

	/**
	 * 处理登陆
	 * @time 2014年11月13日下午12:47:35
	 * @return void
	 * @user ganlinux
	 */
	private void doLogin() {
		SharePreferenceUtil util = new SharePreferenceUtil(this, Constant.SAVE_USERINFO);
		util.setUserName(accountEdit.getText().toString());
		if (rememberPassword.isChecked()) {
			util.setPassword(pwdEdit.getText().toString());
		}else
		{
			util.setPassword("");
		}

		if ((!"".equals(accountEdit.getText().toString().trim()))&&(!"".equals(pwdEdit.getText().toString().trim()))) {
			String pwdString;
			pwdString = MD5.getMD5(pwdEdit.getText().toString());
			showProgressDialog(getString(R.string.login_progresstip), getString(R.string.login_progresstext));
			EMMSPushManager.requestLogin(this,MyApplication.getUserData().getIdIP(),accountEdit.getText().toString(),pwdString);

			canReceive = true;
			mHandler.postDelayed(mRunnable, Constant.LOGIN_TIMEOUT*1000);
		}else
		{
			showToask(getString(R.string.login_password_empty));
		}


	}
	private void doregist(String phone) {

		Intent intent = new Intent(LoginActivity.this,RegisterActivity.class); 
		intent.putExtra("phone", phone);
		startActivity(intent);

	}
	@Override
	public void onReplyReceived(final ReplyBody reply) {
		super.onReplyReceived(reply);
		if (canReceive) 
		{
			if (reply.getType().equals(Constant.TYPE_REGISTER_LOGIN)) {
				hideProgressDialog();
				if(reply.get(Constant.CODE_LOGIN).equals(Constant.LOGIN_SUCCESS))
				{

					String roomsString = "";
					MyApplication.getUserData().setIsOnline(true);
					MyApplication.getUserData().setName(reply.get("username"));
					MyApplication.getUserData().setPhone(reply.get("phonenum"));
					MyApplication.getUserData().setPhoneIsVerify(false);
					MyApplication.getUserData().setPassword(pwdEdit.getText().toString());
					MyApplication.getUserData().setImg(R.drawable.app_panel_friendcard_icon);
					MyApplication.getUserData().setIp("null");
					MyApplication.getUserData().setPort(0);
					MyApplication.getUserData().setMainroom(reply.get("main_room"));
					MyApplication.getUserData().setElseroom(reply.get("elseeoom"));
					if (Integer.parseInt(reply.get("roomnum")) == 1) {
						roomsString = reply.get("main_room");
					}else {
						roomsString = reply.get("main_room")+":"+reply.get("elseeoom");
					}
					MyApplication.getUserData().setCardnum(reply.get("cardnum"));
					MyApplication.getUserData().setLasttime(reply.get("lastlogintime"));

					roomViewEntity = new RoomViewEntity(roomsString,reply.get("dev_state"),reply.get("ye"), reply.get("bjsz"), reply.get("fmzt"), reply.get("zje"), reply.get("jswd"), reply.get("hswd"), reply.get("ls"), reply.get("time"),reply.get("dbye"),reply.get("sbyl"));
					String id = MyApplication.getUserData().getIdIP();
					String username = MyApplication.getUserData().getName();
					EMMSPushManager.requestLoginSync(this,id,username);
					// 隐藏输入法
					InputMethodManager imm = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
					// 显示或者隐藏输入法
					imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
					showToask("登陆成功");

					//mHandler.removeCallbacks(mRunnable);
					//这里存放一些心跳的东西
					new HeartBeatInfoSaveUtil(this).setHeartBeatInfo(id, true, username);
					
					
					Intent intent = new Intent(LoginActivity.this,TabActivity.class);  
					intent.putExtra("RoomView", roomViewEntity);  
					startActivity(intent);
					
					
					finish();

				}else
				{
					String result = "";
					if(reply.get(Constant.CODE_LOGIN).equals(Constant.LOGIN_FAIL))
					{
						result = getString(R.string.login_fail_nameorpasswordwrong);
					}else if(reply.get(Constant.CODE_LOGIN).equals(Constant.LOGIN_USERLOGINREPEAT))
					{
						result = getString(R.string.login_fail_userloginrepeat);
					}else
					{
						result = getString(R.string.login_fail_unknow);
						result += reply.get("login_code");
					}
					showToask(getString(R.string.login_fail) + result);
				}

			}
		}



	}
	@Override
	public void onDestroy() {
		//waveView.stop();
		canReceive = false;
		mHandler.removeCallbacks(mRunnable);
		super.onDestroy();
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.login_btn:
			doLogin();
			break;
		case R.id.regist_btn:
			//打开注册页面
			RegisterPage registerPage = new RegisterPage();
			registerPage.setRegisterCallback(new EventHandler() {
				public void afterEvent(int event, int result, Object data) {
					// 解析注册结果
					if (result == SMSSDK.RESULT_COMPLETE) {
						@SuppressWarnings("unchecked")
						HashMap<String,Object> phoneMap = (HashMap<String, Object>) data;
						//String country = (String) phoneMap.get("country");
						String phone = (String) phoneMap.get("phone");
						// 提交用户信息
						doregist(phone);
					}
				}
			});
			registerPage.show(this);
			//doregist();
			break;
		case R.id.more:
			showMoreView(!mShowMenu);
			break;
		}

	}

	@Override
	public void onBackPressed() {
		if (canReceive) {
			hideProgressDialog();
			canReceive = false;
			mHandler.removeCallbacks(mRunnable);
		}else {
			EMMSPushManager.destory(this);
			MyApplication.getInstance().exit();
		}
		
	}

	public void showMoreView(boolean bShow) {
		if (bShow) {
			mMoreMenuView.setVisibility(View.GONE);
			mMoreImage.setImageResource(R.drawable.login_more_up);
			mShowMenu = true;
		} else {
			mMoreMenuView.setVisibility(View.VISIBLE);
			mMoreImage.setImageResource(R.drawable.login_more);
			mShowMenu = false;
		}
	}
	public void checkUpdate() {
		String curruntVersion = getVersion();
		String lastVersion = MyApplication.getUserData().getLastversion();
		showToask( "lastVersion:"+lastVersion);
		if (lastVersion.equals("null")) {
			return;
		}
		if(Float.valueOf(lastVersion)>Float.valueOf(curruntVersion))
		{
			showToask( "curruntVersion:"+curruntVersion);
			mUpdateManager = new UpdateManager(this);
			mUpdateManager.checkUpdateInfo();
		}else
		{
			showToask( "当前为最新版本");
		}


	}
	public void onUserCancel()
	{
		super.onUserCancel();
		showToask("登陆取消");
		canReceive = false;
		mHandler.removeCallbacks(mRunnable);
	}
}
